import { resultArrange, resultOutApi } from '@a/data';
import { isPreview, intervalUnitHandle, GetProperty } from '@u';

const interPools = {};

// 组件数据，轮询
export const useInterData = (id, config) => {
	if (isPreview() && config.request) {
		if (interPools[id]) clearInterval(interPools[id]);

		const { requestInterval: time, requestIntervalUnit: unit, reqID, requestDataType, pageKey } = config.request;

		// 组件自身请求数据
		if ((requestDataType == 1 && reqID) || (requestDataType == 3 && reqID)) {
			const fetchFn = async function (data) {
				// resultArrange 动态请求、resultOutApi 外部接口
				const res = await (requestDataType == 1 ? resultArrange : resultOutApi)({ id: reqID, ...data });
				if (res) {
					try {
						config.config.data = new Function('data', 'res', config.filter)(res.data, res);
					} catch (err) {
						console.error(err);
					}
				}
			};

			// 初始化执行
			fetchFn();

			// 开启轮询
			if (time) interPools[id] = setInterval(fetchFn, intervalUnitHandle(time, unit));

			// 抛出请求函数
			return fetchFn;
		}

		// 页面数据
		if (requestDataType == 2 && pageKey) {
			watch(
				() => $store.chart.pageData,
				(val) => {
					config.config.data = new Function('data', config.filter)(GetProperty(val, pageKey));
				},
				{ deep: true }
			);
		}
	}
};

export const useClearInterval = (ids) => {
	if (!Array.isArray(ids)) {
		clear(ids);
	} else {
		ids.forEach((id) => {
			clear(id);
		});
	}

	function clear(id) {
		const mark = interPools[id];
		mark && clearInterval(mark);
	}
};

// 页面数据，轮询
export const apgeInterData = (config) => {
	if (isPreview()) {
		const { requestInterval, requestIntervalUnit, requestDataType, reqID, filter } = config;

		if ((requestDataType == 1 && reqID) || (requestDataType == 3 && reqID)) {
			const fetchFn = async function () {
				const res = await (requestDataType == 1 ? resultArrange : resultOutApi)({ id: reqID });
				if (res) {
					try {
						$store.chart.pageData = merge($store.chart.pageData, new Function('data', 'res', filter)(res.data, res));
					} catch (err) {
						console.error(err);
					}
				}
			};
			// 初始化执行
			fetchFn();
			// 开启轮询
			if (requestInterval) setInterval(fetchFn, intervalUnitHandle(requestInterval, requestIntervalUnit));
		}
	}
};
